package com.wwj.auction.login.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.auction.login.entity.UserAccount;
import com.wwj.auction.login.mapper.UserAccountMapper;
import com.wwj.auction.login.service.UserAccountService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-10
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Override
    public void freezeMoney(Integer userId, String fetchAmt) {
        // 查询出当前账户信息
        UserAccount userAccount = baseMapper.selectOne(
                Wrappers.lambdaQuery(UserAccount.class)
                        .eq(UserAccount::getUserId, userId));
        // 获取账户余额
        BigDecimal amount = userAccount.getAmount();
        // 冻结后剩余的金额
        BigDecimal fetchAmtDecimal = new BigDecimal(fetchAmt);
        amount = amount.subtract(fetchAmtDecimal);
        // 保存
        userAccount.setAmount(amount);
        userAccount.setFreezeAmount(fetchAmtDecimal);
        baseMapper.updateById(userAccount);
    }

    @Override
    public void subtractAmount(Integer userId, BigDecimal shopPrice, BigDecimal earnestMoney, BigDecimal shopFreight) {
        // 查询账户
        UserAccount userAccount = baseMapper.selectOne(
                Wrappers.lambdaQuery(UserAccount.class)
                        .eq(UserAccount::getUserId, userId));
        // 总消费 = 拍品价格 + 运费
        BigDecimal totalAmount = shopPrice.add(shopFreight);
        // 扣减
        userAccount.setAmount(userAccount.getAmount().subtract(totalAmount));
        // 解冻保证金
        userAccount.setAmount(userAccount.getAmount().add(earnestMoney));
        userAccount.setFreezeAmount(userAccount.getFreezeAmount().subtract(earnestMoney));
        // 更新
        baseMapper.updateById(userAccount);
    }
}
